<!-- 折线 -->
<template>
  <div class="area-series-item" :class="[containerAreaSeries]"></div>
</template>

<script setup>
import { AreaSeries, CandlestickSeries, createChart } from 'lightweight-charts';
import { onMounted, onUnmounted, ref, watch, watchEffect } from 'vue';

const props = defineProps({
  // 产品ID
  productId: {
    type: [String, Number],
    required: true
  },
  // 产品代码
  productCode: {
    type: String,
    required: true
  },
  // 数据
  dataAreaSeries: {
    type: Array,
    defaults: []
  },
  // 容器class
  containerAreaSeries: {
    type: String
  },
  // 宽
  width: {
    type: String
  },
  // 高
  height: {
    type: String
  },
  // 渐变颜色顶部
  upColor: {
    type: String,
  },
  // 背景颜色
  bgColor: {
    type: String,
  },
  lineColor: String,
  bottomColor: String,
  // 图表类型（line或candle）
  chartType: {
    type: String,
    default: 'line'
  },
  lll: Number
})

const containerAreaSeries = ref(props.containerAreaSeries);
let chartAreaSeries = null;
let areaSeries = null;
let candlestickSeries = null;

// 图表数据
const chartData = ref([]);

// 监听props中的dataAreaSeries变化
watch(() => props.dataAreaSeries, (newData) => {
  console.log(`📈 AreaSeriesItem组件接收到数据 - 产品${props.productId}:`, {
    产品代码: props.productCode,
    数据长度: newData ? newData.length : 0,
    数据样本: newData && newData.length > 0 ? newData.slice(-3) : [],
    数据格式检查: newData && newData.length > 0 ? {
      第一条数据: newData[0],
      时间格式正确: typeof newData[0]?.time === 'number',
      价格格式正确: typeof newData[0]?.value === 'number'
    } : null
  });
  
  // 先保存数据到 chartData，即使 Series 还没创建
  if (newData && Array.isArray(newData) && newData.length > 0) {
    chartData.value = [...newData];
    console.log(`✅ 产品${props.productId}的数据已保存到 chartData`);
    
    // 如果 Series 已经创建，立即更新图表
    if (areaSeries || candlestickSeries) {
      try {
        updateChartSeries(chartData.value);
        chartAreaSeries.timeScale().fitContent();
        console.log(`✅ 产品${props.productId}的K线图表已更新`);
      } catch (error) {
        console.error(`❌ 产品${props.productId}的K线图表更新失败:`, error);
      }
    }
  } else {
    console.log(`⚠️ 产品${props.productId}接收到空数据或无效数据`);
  }
}, { deep: true, immediate: true });

// 监听chartType类型变化
watch(() => props.chartType, (newType) => {
  console.log(`🔄 更改图表类型: ${newType}`);
  if (chartAreaSeries && props.dataAreaSeries && props.dataAreaSeries.length > 0) {
    // 移除旧的Series
    if (areaSeries) {
      chartAreaSeries.removeSeries(areaSeries);
      areaSeries = null;
    }
    if (candlestickSeries) {
      chartAreaSeries.removeSeries(candlestickSeries);
      candlestickSeries = null;
    }
    
    // 根据新类型转换数据
    chartData.value = [...props.dataAreaSeries];
    
    // 添加新的Series
    createChartSeries(newType);
    updateChartSeries(chartData.value);
    chartAreaSeries.timeScale().fitContent();
  }
}, { immediate: false });

let chartAreaSeriesOptions = {
  // 栅格
  grid: {
    vertLines: { visible: false },
    horzLines: { visible: false },
  },
  // 十字线
  crosshair: {
    vertLine: {
      visible: false,
    },
    horzLine: {
      visible: false,
    }
  },
  // 时间轴
  timeScale: {
    visible: false,      // 完全隐藏时间轴
    borderVisible: false // 同时隐藏边框
  },
  // 价格轴
  rightPriceScale: {
    visible: false,      // 隐藏右侧价格轴
    borderVisible: false // 隐藏边框
  },
  handleScroll: true,  // 启用鼠标滚轮缩放
  handleScale: true,   // 启用缩放手势
  kineticScroll: true, // 启用惯性滚动
  layout: {
    textColor: 'black',
    background: {
      color: 'transparent' // 修改为透明
    }
  }
  // 注意: width 不 height 会在 initAreaSeries 中动态设置
};

// 创建图表系列
const createChartSeries = (type) => {
  if (!chartAreaSeries) return;
  
  if (type === 'candle') {
    candlestickSeries = chartAreaSeries.addSeries(CandlestickSeries, {
      upColor: '#26a69a',
      downColor: '#ef5350',
      borderUpColor: '#26a69a',
      borderDownColor: '#ef5350',
      borderVisible: true,
      wickUpColor: '#26a69a',
      wickDownColor: '#ef5350',
      wickVisible: true,
    });
  } else {
    areaSeries = chartAreaSeries.addSeries(AreaSeries, {
      lineColor: props.lineColor,
      topColor: props.upColor,
      bottomColor: props.bottomColor,
      priceLineVisible: false,
      crosshairMarkerVisible: false,
      lineWidth: 2,
    });
  }
};

// 更新图表数据
const updateChartSeries = (data) => {
  if (candlestickSeries) {
    candlestickSeries.setData(data);
  } else if (areaSeries) {
    areaSeries.setData(data);
  }
};

const initAreaSeries = () => {
  if (!containerAreaSeries.value) {
    console.error('❌ 容器class未定义');
    return;
  }
  
  const container = document.querySelector(`.${containerAreaSeries.value}`);
  if (!container) {
    console.error(`❌ 未找到容器元素: .${containerAreaSeries.value}`);
    return;
  }
  
  try {
    // 获取容器的实际尺寸
    const containerWidth = container.clientWidth;
    const containerHeight = container.clientHeight;
    
    // 使用容器实际尺寸，容器高度希应处理
    const options = {
      ...chartAreaSeriesOptions,
      width: containerWidth || 361,
      height: containerHeight > 0 ? containerHeight : 50
    };
    
    chartAreaSeries = createChart(container, options);
    createChartSeries(props.chartType);
    
    // 如果已经有数据，立即渲染
    if (chartData.value && chartData.value.length > 0) {
      updateChartSeries(chartData.value);
      chartAreaSeries.timeScale().fitContent();
      console.log(`✅ 图表初始化时已渲染数据，产品ID: ${props.productId}`);
    }
  } catch (error) {
    console.error(`❌ 图表初始化失败，产品ID: ${props.productId}`, error);
  }
}

// 使用watchEffect监听chartData变化
watchEffect(() => {
  if (!chartAreaSeries) {
    return;
  }
  
  if (chartData.value && Array.isArray(chartData.value) && chartData.value.length > 0) {
    try {
      updateChartSeries(chartData.value);
      chartAreaSeries.timeScale().fitContent();
      console.log(`✅ 通过watchEffect更新图表数据，产品ID: ${props.productId}`);
    } catch (error) {
      console.error(`❌ 通过watchEffect更新图表数据失败，产品ID: ${props.productId}`, error);
    }
  }
})

onMounted(async () => {
  // 初始化图表
  initAreaSeries();
});

onUnmounted(() => {
  // 销毁图表
  if (chartAreaSeries) {
    try {
      chartAreaSeries.remove();
      console.log(`✅ 图表已销毁，产品ID: ${props.productId}`);
    } catch (error) {
      console.error(`❌ 图表销毁失败，产品ID: ${props.productId}`, error);
    }
  }
});

</script>

<style>
a#tv-attr-logo {
  display: none;
}
</style>